export const useWebSocket = (handleMessage: (e: Event) => void) => {
  let TOKEN = window.localStorage.getItem('TOKEN')
  // 测试 
  // let url = `wss://jxcloudlight.com/chain_test_ws/webscoket/server/${TOKEN}`
  // 正式
  let url = `ws://180.184.96.73/chain_ws/webscoket/server/${TOKEN}`
  let ws:any = null;
  console.log('WebSocket' in window)
  let timer:any = null;
    let timer_count = 0;

  const setTime = () => {
    timer_count = 0;
    if(timer != null) {
      clearInterval(timer)
      timer = null
      
    }
    
    timer = setInterval(myTimer, 20000);
  }
  function myTimer() {
      //TODO 如果超过半小时没有交互，则关闭计时器
      if(timer_count >= 1800){
        clearInterval(timer)
        timer = null
        timer_count = 0;
        setTime()
      }else {
          timer_count += 30;
          var online = JSON.stringify({to:'ping'});
          ws.send(online);
          console.log('timer_count',timer_count);
      }
  }
  const init = () => {
    
    console.log(ws)
    ws = new WebSocket(url,)
    bindEvent()
  }

  function bindEvent() {
    ws.addEventListener('open', handleOpen, false);
    ws.addEventListener('close', handleClose, false);
    ws.addEventListener('error', handleError, false);
    ws.addEventListener('message', handleMessage, false);
  }

  function handleOpen(e: Event) {
    console.log('WebSocket Open', e)
    setTime()
  }

  function handleClose(e: CloseEvent) {
    console.log('WebSocket Close', e)
    
    if(e.code === 1006) {
      console.log('重新开启')
      init()
    }
  }
  function handleError(e: Event) {
    console.log('WebSocket Error', e)
    ws.close()
  }
  

  init()

  return ws
}